/**
 * 通用的图表查看组件
 * 支持多种图表类型和显示模式切换
 */

import React from 'react';
import { Empty, Radio, Table } from 'antd';
import { TableOutlined, BarChartOutlined } from '@ant-design/icons';
import { ChartType, DisplayMode, ChartDataPoint, ColumnDefinition, ChartAxisConfig } from './types';
import { prepareChartData } from '../../utils/chartUtils';
import { defaultChartOptions } from '../../config/chartConfig';
import ChartRenderer from './charts/ChartRenderer';

interface ChartViewerProps {
  data: ChartDataPoint[];
  columns: ColumnDefinition[];
  axisConfig?: ChartAxisConfig;
  displayMode?: DisplayMode;
  chartType?: ChartType;
  title?: string;
  onDisplayModeChange?: (mode: DisplayMode) => void;
  onChartTypeChange?: (type: ChartType) => void;
  tableColumns?: any[];
  tableDataSource?: any[];
  loading?: boolean;
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    onChange?: (page: number, pageSize: number) => void;
    onShowSizeChange?: (current: number, size: number) => void;
    showSizeChanger?: boolean;
    showTotal?: (total: number) => string;
  };
}

const ChartViewer: React.FC<ChartViewerProps> = ({
  data,
  columns,
  axisConfig,
  displayMode = 'table',
  chartType = 'column',
  title,
  onDisplayModeChange,
  onChartTypeChange,
  tableColumns,
  tableDataSource,
  loading = false,
  pagination,
}) => {
  // 准备图表数据
  const chartData = React.useMemo(() => {
    if (displayMode !== 'chart') return null;
    return prepareChartData(data, columns, axisConfig);
  }, [data, columns, axisConfig, displayMode]);

  // 根据图表类型获取图表选项
  const getChartOptions = (): any => {
    const baseOptions = {
      ...defaultChartOptions,
      maintainAspectRatio: false, // 禁用宽高比保持，以便更好地控制高度
      plugins: {
        ...defaultChartOptions.plugins,
        title: {
          display: !!title,
          text: title || '',
        },
      },
    };

    return baseOptions;
  };

  // 计算图表高度 - 固定合理的高度，不要根据数据量动态扩展
  const chartHeight = 400;

  return (
    <div>
      {/* 显示模式切换和图表类型选择 */}
      <div
        style={{
          marginBottom: 16,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '8px',
        }}
      >
        <Radio.Group
          value={displayMode}
          onChange={e => onDisplayModeChange?.(e.target.value)}
          size="small"
        >
          <Radio.Button value="table">
            <TableOutlined /> 表格
          </Radio.Button>
          <Radio.Button value="chart">
            <BarChartOutlined /> 图表
          </Radio.Button>
        </Radio.Group>

        {displayMode === 'chart' && (
          <Radio.Group
            value={chartType}
            onChange={e => onChartTypeChange?.(e.target.value)}
            size="small"
            optionType="button"
          >
            <Radio.Button value="column">柱状图</Radio.Button>
            <Radio.Button value="bar">条形图</Radio.Button>
            <Radio.Button value="line">折线图</Radio.Button>
            <Radio.Button value="stepped-line">阶梯折线</Radio.Button>
            <Radio.Button value="waterfall">瀑布图</Radio.Button>
            <Radio.Button value="pie">饼图</Radio.Button>
            <Radio.Button value="doughnut">甜甜圈图</Radio.Button>
            <Radio.Button value="radar">雷达图</Radio.Button>
          </Radio.Group>
        )}
      </div>

      {/* 根据模式显示表格或图表 */}
      {displayMode === 'table' ? (
        tableColumns && tableDataSource ? (
          <Table
            columns={tableColumns}
            dataSource={tableDataSource}
            scroll={{ x: 'max-content' }}
            size="small"
            loading={loading}
            pagination={pagination !== undefined ? pagination : false}
          />
        ) : (
          <Empty description="表格数据不可用" style={{ padding: '40px 0' }} />
        )
      ) : (
        <div style={{ height: `${chartHeight}px`, position: 'relative' }}>
          {!chartData ? (
            <Empty
              description="无法生成图表，请确保数据包含数值类型的列"
              style={{ padding: '40px 0' }}
            />
          ) : (
            <ChartRenderer
              type={chartType}
              data={chartData}
              options={getChartOptions()}
              height={chartHeight}
            />
          )}
        </div>
      )}
    </div>
  );
};

export default ChartViewer;
